package indi.jp.project.center.service.impl;

import indi.jp.project.center.entity.Task;
import indi.jp.project.center.service.TaskService;
import indi.jp.project.core.dao.BaseDao;
import indi.jp.project.core.entity.Datagrid;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.List;

@Service
public class TaskServiceImpl implements TaskService {

    private BaseDao baseDao;

    public TaskServiceImpl(BaseDao baseDao) {
        this.baseDao = baseDao;
    }

    @Override
    public Datagrid<Task> queryGrid(Task entity) throws SQLException {
        Datagrid<Task> datagrid = new Datagrid<>();
        List<Task> list = baseDao.queryList("centerTaskMapper.queryList", entity);
        int count = baseDao.queryCount("centerTaskMapper.queryCount", entity);
        datagrid.setGrid(list);
        datagrid.setTotal(count);
        return datagrid;
    }

//    @Override
//    public int generateTask(Task entity) throws SQLException {
//        return baseDao.insert("centerTaskMapper.generateTask", entity);
//    }

    @Override
    public int completeTask(String taskId, String taskHandler) throws SQLException {
        return baseDao.update("centerTaskMapper.completeTask", taskId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void generateTask(Task task) throws SQLException {
        if (task.getTaskState() == 0 || task.getTaskState() == 99) {
            baseDao.update("centerTaskMapper.completeTask", task.getTaskId());
        } else {
            baseDao.update("centerTaskMapper.completeTask", task.getTaskId());
            baseDao.insert("centerTaskMapper.generateTask", task);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByTaskId(String taskId) throws Exception {
        baseDao.delete("centerTaskMapper.deleteByTaskId", taskId);
    }

}
